//
//  WeatherViewController.m
//  ExploreWorld
//
//  Created by dlios on 15/7/13.
//  Copyright (c) 2015年 chenlin. All rights reserved.
//

#import "WeatherViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "WeatherModel.h"
#import "Header.h"


//----------------------------
#import "NowTemLable.h"
#import "LittleUILable.h"


//----------------------------
//#import "nowTemLable.h"
//#import "LittleUILable.h"

//----------------------------
//未来36小时
#import "Hourly_forecastUILable.h"
//未来几天的天气
#import "ForecastUILable.h"

#import "DrawView.h"

#import "WeatherDetailView.h"

#import "WindView.h"

//日出日落
#import "SunView.h"
@interface WeatherViewController ()

@end

@implementation WeatherViewController

- (void)dealloc
{
    [self.bgScroll release];
    [self.Hourly_forecast release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.forecastArray = [NSMutableArray array];
        self.hourly_forecastArray = [NSMutableArray array];
        self.hourly_temperatureArray = [NSMutableArray array];
        self.point = [NSMutableArray array];
        self.aqiArray = [NSMutableArray array];
        self.ChinaArray = [NSMutableArray array];
        self.sun_phaseArray = [NSMutableArray array];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
    [self weatherNetRequestWithCityName:@"大连"];
}



- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self createBackButton];
    [self createWeatherView];
    [self createHourly_forecastScroll];
    [self createforecastScroll];
    // [self createSunView];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)createBackButton
{
    UIButton *back = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [back addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back];
   // [back setBackgroundColor:[UIColor greenColor]];
    [back release];
}

- (void)backClick:(id)snder
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}



#pragma mark -
#pragma mark 传入定位定到的城市名称，对citys.plist文件进行便利，查找出与城市名字对应的城市cityid，取出来做网址参数进行网络请求

- (void)weatherNetRequestWithCityName:(NSString *)cityName
{
    //对plist文件进行解析
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"citys" ofType:@"plist"];
    NSMutableArray *cityArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    for (NSMutableDictionary *cityDic in cityArray) {
        NSString *str = [cityDic objectForKey:@"cityname"];
        if ([str isEqualToString:cityName]) {
            
            //如果查到这个城市，进行天气数据的网络请求
          //  NSLog(@"%@",[cityDic objectForKey:@"cityname"]);
           //  NSLog(@"%@",[cityDic objectForKey:@"cityid"]);
            [self  netConnectFromWeatherForcastWithCityID:[cityDic objectForKey:@"cityid"]];
            [self netConnectFromChinaWeatherWithCityID:[cityDic objectForKey:@"cityid"]];
        }
 
    }
    
}

#pragma mark -
#pragma mark 从天气预报抓的接口的网络请求

-(void)netConnectFromWeatherForcastWithCityID:(NSString *)cityID
{
    
    //对未来几天进行网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   [ manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    
    NSString *str1 = [NSString stringWithFormat:@"http://weather.ios.ijinshan.com/api/forecasts?cc=w-%@",cityID] ;
    // NSLog(@"%@", str1);
    [manager GET:str1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        

            NSData *data = operation.responseData;
            //超大字典
            NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            
            ////解析未来几天的天气数据，从这个字典里拿出未来几天的数据，存放到forecast数组里
            NSMutableDictionary *Dic = [BigDic objectForKeyedSubscript:@"forecast"];
            NSMutableArray *Array = [Dic objectForKey:[NSString stringWithFormat:@"w-%@",cityID]];
        for (NSMutableDictionary *dic in Array) {
            
                WeatherModel *model = [[WeatherModel alloc]init];
                model.date = [dic objectForKey:@"date"];
                model.tz = [dic objectForKey:@"tz"];
                model.d = [dic objectForKey:@"d"];
                model.aqi = [dic objectForKey:@"aqi"];
                model.grade = [dic objectForKey:@"grade"];
                model.tn = [dic objectForKey:@"tn"];
                model.tn_f = [dic objectForKey:@"tn_f"];
                model.tl = [dic objectForKey:@"tl"];
                model.tl_f = [dic objectForKey:@"tl_f"];
                model.th = [dic objectForKey:@"th"];
                model.th_f = [dic objectForKey:@"th_f"];
                NSMutableArray *wd = [dic objectForKey:@"wd"];
                model.wd = wd[0];
                NSMutableArray *ws = [dic objectForKey:@"ws"];
                model.ws = ws[0];
                NSMutableArray *kph = [dic objectForKey:@"kph"];
                model.kph =  kph[0];
                NSMutableArray *mph = [dic objectForKey:@"mph"];
                model.mph = mph[0];
                model.fl_f = [dic objectForKey:@"fl_f"];
                model.fl = [dic objectForKey:@"fl"];
                model.rh = [dic objectForKey:@"rh"];
                model.p_mb = [dic objectForKey:@"p_mb"];
                model.pt = [dic objectForKey:@"pt"];
                [ self.forecastArray addObject:model];
      
        }
    //解析未来36小时的数据，从这个字典里拿出未来36小时的数据，存放到forecast数组里
        NSMutableDictionary *secondDic = [BigDic objectForKey:@"hourly_forecast"];
        NSMutableArray *bigArray = [secondDic objectForKey:[NSString stringWithFormat:@"w-%@",cityID]];
        for (NSMutableDictionary *dic in bigArray) {
            WeatherModel *model = [[WeatherModel alloc]init];
            model.h = [dic objectForKey:@"h"];
            NSMutableArray *kphArray = [dic objectForKey:@"kph"];
            model.kph = kphArray[0];
            model.tm = [dic objectForKey:@"tm"];
            [self.hourly_forecastArray addObject:model];
            [self.hourly_temperatureArray addObject:model.tm];
        }
        
        //实时天气具体
        NSMutableDictionary *aqi = [BigDic objectForKey:@"aqi"];
        NSMutableDictionary *locDic = [aqi objectForKey:[NSString stringWithFormat:@"w-%@",cityID]];

            WeatherModel *model = [[WeatherModel alloc]init];
            model.aqi = [locDic objectForKey:@"aqi"];
            model.pm25 = [locDic objectForKey:@"pm25"];
            model.grade = [locDic objectForKey:@"grade"];
            [self.aqiArray addObject:model];

        //解析出日出日落时间
        NSMutableDictionary *podic = [BigDic objectForKey:@"sun_phase"];
        NSMutableDictionary *opDic = [podic objectForKey:[NSString stringWithFormat:@"w-%@",cityID]];
       // NSMutableDictionary *td = [opDic objectForKey:@"td"];
        NSMutableDictionary *td = [opDic objectForKey:@"td"];
         WeatherModel *model1 = [[WeatherModel alloc]init];
        model1.ss = [td objectForKey:@"ss"];
        model1.sr = [td objectForKey:@"sr"];
        [self.sun_phaseArray addObject:model1];
        [self createforecastLable];
        [self createHourly_forecastLable];
        [self createWeatherDetailView];
        [self createSunView];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

    

}


#pragma mark -
#pragma mark 创建天气界面
- (void)createWeatherView
{

    self.bgScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT )];
    [self.bgScroll setContentSize:CGSizeMake(0, HEIGHT * 7)];
    [self.view addSubview:self.bgScroll];

   
    //城市名称
    UILabel *city = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    [city setCenter:CGPointMake(WIDTH / 2, 20)];
    [city setText:@"大连"];
    [city setTextAlignment:NSTextAlignmentCenter];
    [city setBackgroundColor:[UIColor grayColor]];
    [city setFont:[UIFont systemFontOfSize:18]];
    [city setTextColor:[UIColor redColor]];
    [self.bgScroll addSubview:city];
    [city release];
    
    UIImageView *share = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - 40, 10, 30, 30)];
    [share setBackgroundColor:[UIColor blackColor]];
    [self.bgScroll addSubview:share];
    [share setImage:[UIImage imageNamed:@"share.png"]];
    [share release];

    
    NowTemLable *nowTem = [[NowTemLable alloc]initWithFrame:CGRectMake(0, 80, 200, 140)];
    [self.bgScroll addSubview:nowTem];
    [nowTem release];
    
    LittleUILable *weather = [[LittleUILable alloc]initWithFrame:CGRectMake(0, 220, 200, 20)];
    [self.bgScroll addSubview:weather];
    [weather setBackgroundColor:[UIColor blackColor]];
    [weather release];
    
    LittleUILable *PM25 = [[LittleUILable alloc]initWithFrame:CGRectMake(0, 240, 200, 20)];
    [self.bgScroll addSubview:PM25];
    [PM25 setBackgroundColor:[UIColor grayColor]];
    [PM25 release];
    
    
    LittleUILable *grade = [[LittleUILable alloc]initWithFrame:CGRectMake(0, 260, 200, 20)];
    [self.bgScroll addSubview:grade];
    [grade setBackgroundColor:[UIColor grayColor]];
    [grade release];

}


#pragma mark -
#pragma mark 创建未来36小时天气的滚动视图
- (void)createHourly_forecastScroll
{
    self.Hourly_forecast = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 300, WIDTH, 280)];
    [self.Hourly_forecast setContentSize:CGSizeMake(36 * 40, 0)];
    [self.bgScroll addSubview:self.Hourly_forecast];
    [self.Hourly_forecast setBackgroundColor:[UIColor grayColor]];
   
}

//把小时Lable添加到 self.Hourly_forecast 滚动视图上
- (void)createHourly_forecastLable
{
     //找出这个数组里最大气温和最小气温
    int maxTem = 0;
    int minTem = 100;
    for (int i = 0; i < self.hourly_temperatureArray.count; i ++) {
        NSString *str = self.hourly_temperatureArray[i];
        float x = [str floatValue];
        maxTem = maxTem > x ? maxTem :x;
        minTem = minTem < x ? minTem :x;
        
    }
    NSLog(@"maxTem = %d",maxTem);
    NSLog(@"minTem = %d",minTem);
    int  wencha = maxTem - minTem;
    
    for (int i = 0; i < 36; i ++) {
        Hourly_forecastUILable *lable = [[Hourly_forecastUILable alloc]initWithFrame:CGRectMake(40 * i, 0, 40, 280)];

        WeatherModel *model  =  self.hourly_forecastArray[i];
         lable.timeLable.text = model.h;
        lable.windLable.text = model.kph;
        
        lable.tag = i + 1;
        float nowTem = [model.tm floatValue];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 5, 5)];
        [imageView setBackgroundColor:[UIColor blackColor]];
        [imageView setCenter:CGPointMake(lable.rangeLable.frame.size.width / 2, 160 / wencha * (nowTem - minTem) + 160 ) ];
        [lable addSubview:imageView];
        
        model.X =  imageView.frame.origin.x;
        model.Y =  160 / wencha * (nowTem - minTem) + 160 ;
        NSLog(@"%f %f",model.X,model.Y);
        [self.point addObject:model];
        [self.Hourly_forecast addSubview:lable];
    }
    
    DrawView *draw = [[DrawView alloc]init];
    draw.arr = [NSMutableArray array];
    [draw.arr addObjectsFromArray:self.point];
    [draw setFrame:CGRectMake(0,120, 36 * 40, 160)];
    [draw setBackgroundColor:[UIColor clearColor]];
    [self.Hourly_forecast addSubview:draw];
}

#pragma mark -
#pragma mark 未来36小时的天气的滚动视图
- (void)createforecastScroll
{
    
    self.forecast = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 600, WIDTH, 300)];
    [self.forecast  setContentSize:CGSizeMake(1000, 0)];
    [self.bgScroll addSubview:self.forecast];
 }

//创建未来几天的lable
- (void)createforecastLable
{
    for (int i = 0; i < self.forecastArray.count; i ++) {
        WeatherModel *model = self.forecastArray[i];
        ForecastUILable *forecast = [[ForecastUILable alloc]initWithFrame:CGRectMake(60 * i, 0, 60, 300)];
        forecast.dLable.text = model.d;
        forecast.dateLable.text = model.date;
        forecast.forecastTHLable.text = [NSString stringWithFormat:@"%@",model.th];
        forecast.forecastTLLable.text = [NSString stringWithFormat:@"%@",model.tl];
 
        if (i / 2 == 0) {
            [forecast.forecastImageView setBackgroundColor:[UIColor grayColor]];
            [forecast.forecasTitletLable setBackgroundColor:[UIColor purpleColor]];
        }
        else
        {
            [forecast.forecasTitletLable setBackgroundColor:[UIColor grayColor]];
            [forecast.forecastImageView setBackgroundColor:[UIColor purpleColor]];

        }

        forecast.tag = 100 * (i - 1);
        [self.forecast addSubview:forecast];
    }
}


#pragma mark -
#pragma mark 创建今日天气详情
- (void)createWeatherDetailView
{
    
    
    WeatherModel *model = self.aqiArray[0];
    
    
    
    WeatherDetailView *detailView = [[WeatherDetailView alloc]initWithFrame:CGRectMake(0, 1000, WIDTH, WIDTH / 2)];
    [self.bgScroll addSubview:detailView];
    detailView.gradeLable.text = model.grade;
   // detailView.  = model.temp_day_tq;
    detailView.PM25.text = model.pm25;
   [detailView setBackgroundColor:[UIColor grayColor]];
    
    [detailView release];
}




#pragma mark -
#pragma mark - 从中国天气抓获取数据

-(void)netConnectFromChinaWeatherWithCityID:(NSString *)cityID
{
    
    //对未来几天进行网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [ manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    
    NSString *str = [NSString stringWithFormat:@"http://chinaweather.cloudapp.net/Default.aspx?city=%@&id=955d8868-a276-4425-aef6-32077b1006d0",cityID] ;
   // NSLog(@"%@", str);
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
     
        
        NSData *data = operation.responseData;
        //超大字典
        NSDictionary *BigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

      //  NSLog(@"%@",BigDic);
     //   NSString *str = [NSString stringWithFormat:@"temp%d",i];
        
                
                for (int i = 1;i <= 7  ; i ++) {
                    
                    
                    
                      for (NSString *key in BigDic) {
                          
                          
                          
                   NSString *str = [NSString stringWithFormat:@"temp%d",i];
                    if ([key rangeOfString:str].location != NSNotFound) {
                        NSString *temp_day_tq = [NSString stringWithFormat:@"%@_day_tq",str];
                        NSString *temp_day_tq_img = [NSString stringWithFormat:@"%@_day_tq_img",str];
                        NSString *temp_date = [NSString stringWithFormat:@"%@_date",str];
                        WeatherModel *model = [[WeatherModel alloc]init];
                        model.sk_sd = [BigDic objectForKey:@"sk_sd"];
                        model.sk_fx = [BigDic objectForKey:@"sk_fx"];
                        model.sk_fl = [BigDic objectForKey:@"sk_fl"];
                        model.temp_day_tq = [BigDic objectForKey:@"temp_day_tq"];
                        model.temp_day_tq_img = [BigDic objectForKey:@"temp_day_tq_img"];
                        model.temp_date = [BigDic objectForKey:@"temp_date"];
                        [self.ChinaArray addObject:model];
                      //  NSLog(@"%@",str);
                        break;
                    }
                }
            }
        [self createWeatherDetailView];
        [self createWindView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

#pragma mark -
#pragma mark 创建风的view
- (void)createWindView

{
    WindView *wind = [[WindView alloc]initWithFrame:CGRectMake(0, 1000 + WIDTH, WIDTH, WIDTH / 2)];
    [wind setBackgroundColor:[UIColor grayColor]];
    WeatherModel *model = self.ChinaArray[0];
      wind.sk_fx.text = model.sk_fx;
    wind.sk_fl.text = model.sk_fl;
    [self.bgScroll addSubview:wind];
}

#pragma mark -
#pragma 太阳view
- (void)createSunView
{
    WeatherModel *model = self.sun_phaseArray[0];
    
    SunView *sun = [[SunView alloc]initWithFrame:CGRectMake(0, 1000 + WIDTH * 2, WIDTH , WIDTH / 2)];
    [sun setBackgroundColor:[UIColor grayColor]];
    sun.ssLable.text = model.ss;
    sun.srLable.text  = model.sr;
    [self.bgScroll addSubview:sun];
  //对日出日落时间进行字符串截取，放到数组里
    NSArray *second = [model.ss componentsSeparatedByString:@":"];
    NSArray *first = [model.sr componentsSeparatedByString:@":"];
    float firsth = [first[0] floatValue];
    float firstm = [first[0] floatValue];
    float secondh = [second[0] floatValue];
    float secondm = [second[0] floatValue];
  
    
    //获取当前时间
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay| NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    float Hour = (float) [dateComponent hour];
    float minu = (float) [dateComponent minute];
    
    float p =  (secondh - firsth) * 60 + secondm - firstm;
    float h = (Hour - firsth) * 60 + minu - firstm;
    float as = p / h * 200;
    NSLog(@"%f",as); //距离日出点坐标的距离
    
    
    if (Hour > firsth && Hour < secondh) {
        CALayer *myLayer=[CALayer layer];
        //设置layer的属性
        myLayer.bounds=CGRectMake(0, 0, 201, 101);
        myLayer.backgroundColor=[UIColor grayColor].CGColor;
        myLayer.position=CGPointMake(19, sun.frame.size.height - 119 );
        myLayer.anchorPoint=CGPointMake(0, 0);
        //添加layer
        // [sun.layer addSublayer:myLayer];
        sun.userInteractionEnabled = YES;
        [sun.layer addSublayer:myLayer];
        
        CABasicAnimation *anima=[CABasicAnimation animationWithKeyPath:@"bounds"];
        //1.1设置动画执行时间
        anima.duration = 2.0;
        //1.2设置动画执行完毕后不删除动画
        anima.removedOnCompletion= NO;
        //1.3设置保存动画的最新状态
        anima.fillMode=kCAFillModeForwards;
        //1.4修改属性，执行动画
        anima.toValue=[NSValue valueWithCGRect:CGRectMake(0, 0, 300 - as, 100)];
        //2.添加动画到layer
        [myLayer addAnimation:anima forKey:nil];
    }
}







-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //1.创建动画
    CABasicAnimation *anima=[CABasicAnimation animationWithKeyPath:@"bounds"];
    //1.1设置动画执行时间
    anima.duration = 2.0;
    //1.2设置动画执行完毕后不删除动画
    anima.removedOnCompletion=NO;
    //1.3设置保存动画的最新状态
    anima.fillMode=kCAFillModeForwards;
    //1.4修改属性，执行动画
    anima.toValue=[NSValue valueWithCGRect:CGRectMake(0, 0, 50, 100)];
    //2.添加动画到layer
    [self.myLayer addAnimation:anima forKey:nil];
}





@end
